package dao

import (
	"log"
	"testhttp/datasource"
	"testhttp/model"
	"time"
)

//add接口
func InsertRules(ruledata []model.MapRules) (int64, error) {

	affact, err := datasource.InstanceMaster().Insert(ruledata)
	if err != nil {
		log.Println("Error InsertRules :", err)
	} else {
		log.Printf("%d records Insert into MapRules.\n", affact)
	}

	return affact, err
}

//list接口
func ListRules() []map[string]interface{} {
	sql := "select imp_exl_name,count(*) as count from map_rules where is_deleted = 0 group  by imp_exl_name ;" // having count(*)>1
	affected, _ := datasource.InstanceMaster().QueryInterface(sql, "rule_uid", "exp_exl_name", "imp_exl_name", "count")

	return affected

}

//list接口,新
func ListRule(page int, pagesize int) ([]model.MapRules, error) {
	rules := make([]model.MapRules, 0)
	offset := (page - 1) * pagesize
	err := datasource.InstanceMaster().Cols("rule_uid", "rule_name", "dealer_id").Where("is_deleted =?", 0).Limit(pagesize, offset).GroupBy("rule_uid").Find(&rules)
	if err != nil {
		log.Print(err)
	}
	// log.Print(rules)
	return rules, err
}

//list接口count数据
func CountRules() int64 {
	count := new(model.MapRules)
	affact, err := datasource.InstanceMaster().Table("map_rules").Where("is_deleted =?", 0).GroupBy("rule_uid").Count(count)
	if err != nil {
		log.Println("query is :", err)
	}
	return affact
}

//view接口
func SelectRulebyId(ruleuid string) []model.MapRules {
	// log.Println("uid is :", ruleuid)
	viewdata := []model.MapRules{}
	err := datasource.InstanceMaster().Table("map_rules").Where("rule_uid = ?", ruleuid).Find(&viewdata)
	if err != nil {
		log.Println("query is :", err)
	} else {
		log.Println("data is :", viewdata)
	}
	return viewdata
}
func SelectRulebyDealerid(dealerid string) []model.MapRules {
	// log.Println("uid is :", ruleuid)
	viewdata := []model.MapRules{}
	err := datasource.InstanceMaster().Table("map_rules").Where("dealer_id = ?", dealerid).Find(&viewdata)
	if err != nil {
		log.Println("query is :", err)
	} else {
		log.Println("data is :", viewdata)
	}
	return viewdata
}

//edit接口
func UpdateRules(ruleuid string) {

}

//del接口
func DeleteRules(rules []model.MapRules) {
	now := time.Now()
	date := &model.MapRules{IsDeleted: 1, UpdateTime: now}
	log.Print("Debug rules:", rules)
	for x := 0; x < len(rules); x++ {
		ok, err := datasource.InstanceMaster().Table("map_rules").Where("rule_uid = ?", rules[x].RuleUid).Cols("is_deleted", "update_time").Update(date)
		if err != nil {
			log.Println("query is :", err)
		} else {
			log.Println("data is :", ok)

		}
	}
}
